package apptoko.com.fragment;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ListFragment;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import apptoko.com.AboutActivity;
import apptoko.com.AccountActivity;
import apptoko.com.AppManageActivity;
import apptoko.com.AppStoreVnApplication;
import apptoko.com.BirthdayDialogActivity;
import apptoko.com.HomeActivity;
import apptoko.com.LoginActivity;
import apptoko.com.RegisterActivity;
import apptoko.com.SettingsActivity;
import apptoko.com.UILApplication;
import apptoko.com.HomeActivity.ISlidingMenuClosed;
import apptoko.com.adapter.ErrorHandler;
import apptoko.com.adapter.SectionListAdapter;
import apptoko.com.background.BackgroundTasks;
import apptoko.com.background.ContentNetworkInterface;
import apptoko.com.db.DatabaseHelper;
import apptoko.com.event.Event;
import apptoko.com.event.Event.BankTYMFailEvent;
import apptoko.com.event.Event.CheckUserBirthdayFailedWithMsg;
import apptoko.com.event.Event.CheckUserBirthdaySucceed;
import apptoko.com.event.Event.ExchangeTYMSuccessEvent;
import apptoko.com.event.Event.FinishActivityEvent;
import apptoko.com.event.Event.GetAccessTokenFailEvent;
import apptoko.com.event.Event.GetAccessTokenSuccessEvent;
import apptoko.com.event.Event.GetSettingDetailsListSuccess;
import apptoko.com.event.Event.GetSettingListSuccess;
import apptoko.com.event.Event.GiftCodeEvent;
import apptoko.com.event.Event.LoginEvent;
import apptoko.com.event.Event.LogoutEvent;
import apptoko.com.event.Event.LogoutFailed;
import apptoko.com.event.Event.PaypalTYMFailEvent;
import apptoko.com.event.Event.ReportGiftboxSuccess;
import apptoko.com.event.Event.RequestTokenEvent;
import apptoko.com.event.Event.SMSTYMFailEvent;
import apptoko.com.event.Event.TopupFailEvent;
import apptoko.com.event.Event.TopupSuccessEvent;
import apptoko.com.event.Event.UserInfoFailEvent;
import apptoko.com.event.Event.UserInfoSuccessEvent;
import apptoko.com.model.AccessToken;
import apptoko.com.model.BankPayment;
import apptoko.com.model.GiftSetting;
import apptoko.com.model.UserInfo;
import apptoko.com.network.HttpHelper;
import apptoko.com.network.IDownloadUpdateCallback;
import apptoko.com.network.ProgressDialogManager;
import apptoko.com.util.CommonUtils;
import apptoko.com.util.Constants;
import apptoko.com.util.Utils;
import apptoko.com.view.AlertDialogManager;
import apptoko.com.view.FeedBackDialog;
import apptoko.com.view.MyWebView;
import apptoko.com.view.UserManualView;

import com.androidquery.AQuery;
import com.appota.ads.callback.AppotaReceiver;
import com.appota.ads.sdk.AppotaAds;
import com.appota.asdk.commons.AccessTokenUtil;
import apptoko.com.R;
import com.devspark.appmsg.AppMsg;
import com.google.analytics.tracking.android.EasyTracker;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.util.AsyncExecutor;
import de.greenrobot.event.util.AsyncExecutor.RunnableEx;

@SuppressLint("CutPasteId")
public class MenuFragment extends ListFragment implements OnClickListener, OnItemClickListener, IDownloadUpdateCallback {
	
	private SectionListAdapter parentAdapter;
	private MenuListAdapter settingAdapter;
	private View userInfo;
	private EventBus eventBus;
	private MenuListItem logout;
	private BackgroundTasks bgTask;
	private ProgressDialog pDialog;
	private ProgressDialog pCancelableDialog;
	private AQuery aq;
	private AQuery aQuery;
	private boolean isLogin = false;
	private int enableFreeTym;
	private String userName = "";
	private String SCENARIO;
	private String accessToken;
	private int greenTym = 0;
	private int purpleTym = 0;
	private DatabaseHelper db;
	private Typeface tf;
	private String birthday;
	private boolean is_check_birthday=false;
	private CPIAReceiver receiver;
	private String countryCode;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setRetainInstance(true);
		registerCPIAReceiver();
		registerReloadLogin();
		countryCode = Utils.getStaticCountryCode(getActivity());
		tf = Typeface.createFromAsset(getActivity().getAssets(), getResources().getString(R.string.roboto_light));
		eventBus = EventBus.getDefault();
		eventBus.register(this);
		bgTask = new BackgroundTasks(getActivity());
		aq = new AQuery(getActivity());
		aq.overridePendingTransition5(R.anim.fade_in, R.anim.fade_in);
		pDialog=new ProgressDialog(getActivity());
		pDialog.setCancelable(false);
		pCancelableDialog=new ProgressDialog(getActivity());
		pCancelableDialog.setCancelable(true);
		pCancelableDialog.setMessage("Loading Manual");
		enableFreeTym = getActivity().getSharedPreferences(Constants.SHARED_NAME, Activity.MODE_PRIVATE).getInt(ContentNetworkInterface.ENABLE_FREE_TYM, 0);
//		TapjoyConnect.enableLogging(true);
//		TapjoyConnect.requestTapjoyConnect(getActivity().getApplicationContext(), "3622bb41-0c54-4057-8dc3-4defc6bf0e34", "JJpYVzmkeqJJOF0NqgqY");
//		TapjoyConnect.getTapjoyConnectInstance().setUserID("user");
		db = new DatabaseHelper(getActivity());
//		checkGift();
//		syncGift();
//		checkNoticeUserUsage();
		checkAccessToken();
	}
	
	private void checkAccessToken(){
//		SharedPreferences shared=PreferenceManager.getDefaultSharedPreferences(getActivity());
//		if(shared.getString("samsung", "").equals("")){
//			shared.edit().putString("at", "3de71f9e84a325bbfb86466c15b40b1e").commit();
//			((AppStoreVnApplication)getActivity().getApplication()).setAccessToken("3de71f9e84a325bbfb86466c15b40b1e");
//		}else{
//			this.accessToken=shared.getString("atk", "3de71f9e84a325bbfb86466c15b40b1e");
//			((AppStoreVnApplication)getActivity().getApplication()).setAccessToken(accessToken);
//		}
		if(AccessTokenUtil.getInstance().init(getActivity()).getSavedAccessToken()!=null && !AccessTokenUtil.getInstance().init(getActivity()).getSavedAccessToken().equals("")){
			((AppStoreVnApplication)getActivity().getApplication()).setAccessToken(AccessTokenUtil.getInstance().init(getActivity()).getSavedAccessToken());
			accessToken=AccessTokenUtil.getInstance().init(getActivity()).getSavedAccessToken();
		}else{
			((AppStoreVnApplication)getActivity().getApplication()).setAccessToken("3de71f9e84a325bbfb86466c15b40b1e");
			accessToken="3de71f9e84a325bbfb86466c15b40b1e";
		}
		((AppStoreVnApplication) getActivity().getApplication()).setAccessToken(accessToken);
		try{
			if(accessToken.equals("3de71f9e84a325bbfb86466c15b40b1e")){
				aq.id(R.id.ll_user_info).visibility(View.GONE);
				Log.e("disable ll_user_info","disable ll_user_info");
			}else{
				aq.id(R.id.ll_user_info).visibility(View.VISIBLE);
				Log.e("visible ll_user_info","visible ll_user_info");
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
//		pDialog.show();
//		accessToken = AccessTokenUtil.getInstance().init(getActivity()).getSavedAccessToken();
//		String expired = AccessTokenUtil.getInstance().init(getActivity()).getAccessTokenExpires();
//		if(TextUtils.isEmpty(accessToken)){
//			bgTask.getRequestToken();
//			return;
//		}
//		if(Utils.checkExpired(expired)){
//			bgTask.getRequestToken();
//		} else {
//			((AppStoreVnApplication) getActivity().getApplication()).setAccessToken(accessToken);
//			pDialog.dismiss();
//		}
	}
	
	private void checkNoticeUserUsage() {
		final SharedPreferences sharedPref = getActivity().getSharedPreferences(Constants.SHARED_NAME, Activity.MODE_PRIVATE);
		boolean notice=sharedPref.getBoolean("_notice", false);
		if(!notice){
			AlertDialog.Builder builder=new Builder(getActivity());
			builder.setTitle(R.string.user_manual).setMessage(R.string.user_manual_msg).setCancelable(false)
			.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					SharedPreferences.Editor editor= sharedPref.edit();
					editor.putBoolean("_notice", true).commit();
				}
			}).show();
		}
	}
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View parent = inflater.inflate(R.layout.list_menu, null);
		userInfo = inflater.inflate(R.layout.menu_user_info, null);
		userInfo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent account = new Intent(getActivity(), AccountActivity.class);
				startActivity(account);
			}
		});
		aQuery = new AQuery(userInfo);
		isLogin = Utils.getStaticIsLogin(getActivity());
		if(isLogin){
			String accessToken = Utils.getStaticAccessToken(getActivity());
			if(accessToken!="3de71f9e84a325bbfb86466c15b40b1e"){
				bgTask.getUserInfo(accessToken);
			}
		} else {
			aQuery.id(R.id.btn_menu_login).clicked(this);
			aQuery.id(R.id.btn_menu_register).clicked(this);
			aQuery.id(userInfo).clicked(null);
		}
		return parent;
	}
	
	private void registerCPIAReceiver(){
		receiver = new CPIAReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(com.appota.ads.commons.Constants.ACTION_RECEIVE);
		getActivity().registerReceiver(receiver, filter);
	}
	private ReloadLogin loginReceiver;
	private void registerReloadLogin(){
		loginReceiver = new ReloadLogin();
		IntentFilter filter = new IntentFilter();
		filter.addAction("LOGGEDIN_AND_RELOAD");
		getActivity().registerReceiver(loginReceiver, filter);
	}
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		Resources res = getResources();
		parentAdapter = new SectionListAdapter(getActivity(), 1);
		
		List<MenuListItem> newsList = new ArrayList<MenuFragment.MenuListItem>();
		newsList.add(new MenuListItem(res.getString(R.string.news_feed), R.drawable.ic_news, 0));
		MenuListAdapter newsAdapter = new MenuListAdapter(getActivity(), R.layout.row, newsList);
		
		List<MenuListItem> manageContent = new ArrayList<MenuFragment.MenuListItem>();
		manageContent.add(new MenuListItem(getResources().getString(R.string.manage), R.drawable.ic_trangchu, 0));
		MenuListAdapter contentAdapter = new MenuListAdapter(getActivity(), R.layout.row, manageContent);
		
//		List<MenuListItem> giftList = new ArrayList<MenuFragment.MenuListItem>();
//		giftList.add(new MenuListItem(res.getString(R.string.lucky_spin), R.drawable.ic_slot, 0));
//		giftList.add(new MenuListItem(res.getString(R.string.shop_activity_title),R.drawable.gifts_4, 0));
//		giftList.add(new MenuListItem(res.getString(R.string.giftcode),R.drawable.gift_code, 0));
//		giftList.add(new MenuListItem(res.getString(R.string.free_tym_metaps),R.drawable.tym_green, 0));
//		giftList.add(new MenuListItem(res.getString(R.string.free_tym_purple),R.drawable.tym_purple, 0));
//		giftList.add(new MenuListItem(res.getString(R.string.free_tym_Apptoko),R.drawable.tym_yellow, 0));
//		MenuListAdapter giftAdapter = new MenuListAdapter(getActivity(), R.layout.row, giftList);
//
//		List<MenuListItem> tymList = new ArrayList<MenuFragment.MenuListItem>();
//		//tymList.add(new MenuListItem(res.getString(R.string.buy_tym_sms), R.drawable.ic_sms, 0));
//		tymList.add(new MenuListItem(res.getString(R.string.buy_tym), R.drawable.ic_card, 0));
//		//tymList.add(new MenuListItem(res.getString(R.string.buy_tym_bank), R.drawable.ic_bank, 0));
//		//tymList.add(new MenuListItem(res.getString(R.string.buy_tym_paypal), R.drawable.ic_paypal, 0));
//		tymList.add(new MenuListItem(res.getString(R.string.exchange_tym), R.drawable.ic_exchange, 0));
//		//tymList.add(new MenuListItem(res.getString(R.string.giftcode), R.drawable.gift, 0));
//		MenuListAdapter buyTYMAdapter = new MenuListAdapter(getActivity(), R.layout.row, tymList);

		List<MenuListItem> settingsList = new ArrayList<MenuFragment.MenuListItem>();
		settingsList.add(new MenuListItem(res.getString(R.string.system), R.drawable.ic_caidat, 0));
		settingsList.add(new MenuListItem(res.getString(R.string.feed_back),R.drawable.feedback, 0));
		settingsList.add(new MenuListItem(res.getString(R.string.user_manual),R.drawable.ic_manual, 0));
		settingsList.add(new MenuListItem(res.getString(R.string.about_setting),R.drawable.ic_about, 0));
		logout = new MenuListItem(res.getString(R.string.logout), R.drawable.ic_logout, 0);
		settingAdapter = new MenuListAdapter(getActivity(), R.layout.row, settingsList);
		
		parentAdapter.addSection(res.getString(R.string.news), newsAdapter);
		parentAdapter.addSection(res.getString(R.string.box), contentAdapter);
//		if(countryCode.equalsIgnoreCase("vn")){
//			parentAdapter.addSection(res.getString(R.string.gift_for_you), giftAdapter);
//			parentAdapter.addSection(res.getString(R.string.tym_transaction), buyTYMAdapter);
//		}
		parentAdapter.addSection(res.getString(R.string.setting), settingAdapter);

		getListView().addHeaderView(userInfo);
		getListView().setDivider(new ColorDrawable(R.color.black));
		getListView().setDividerHeight(1);
		setListAdapter(parentAdapter);
		getListView().setOnItemClickListener(this);
	}
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		Log.e("onResume","onResumeMenuFragment");
		super.onResume();
		if(enableFreeTym == 1){
			try {
//				MetapsFactory.startReward(getActivity(), new MyReceiver(), "user", SCENARIO, true, Long.valueOf(30*1000));
				//MetapsFactory.confirmOfferResultAll();
			} catch (Exception e) {
				e.printStackTrace();
				Log.e("SampleActivity", "Exception : "+e.getClass().getName()+" "+e.getMessage());
			}
		}
	}
	public void onEventMainThread(FinishActivityEvent event){
		Log.e("FinishActivityEvent","FinishActivityEvent");
		getActivity().finish();
	}
	
	
	public void onEventMainThread(LoginEvent event){
		//pDialog = new ProgressDialogManager().showProgressDialog(getActivity(), R.string.loading);
		Log.e("doLogin","doLogin f mf");
		String newaccessToken=event.access_token;
		if(!TextUtils.isEmpty(newaccessToken)&&newaccessToken!="3de71f9e84a325bbfb86466c15b40b1e"){
			accessToken=newaccessToken;
			doReload(accessToken);
		}
		
//		eventBus.post(new Event.CloseAfterLoginTwitter());
	}

	private void doReload(String tk) {
		if(!TextUtils.isEmpty(tk)&&tk!="3de71f9e84a325bbfb86466c15b40b1e"){
			accessToken=tk;
		}
		bgTask.getUserInfo(accessToken);
		aq.id(R.id.btn_menu_login).gone();
		aq.id(R.id.btn_menu_register).gone();
		aq.id(R.id.btn_menu_login).clicked(null);
		aq.id(R.id.btn_menu_register).clicked(null);
		aQuery.id(userInfo).clicked(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent account = new Intent(getActivity(), AccountActivity.class);
				startActivity(account);
			}
		});
		((AppStoreVnApplication) getActivity().getApplication()).setAccessToken(accessToken);
		((AppStoreVnApplication) getActivity().getApplication()).setLogin(true);
	}
	
	public void onEventMainThread(UserInfoFailEvent event){
		//ErrorHandler.getInstance().setContext(getActivity()).handleError(event.getErrorCode());
		if(pDialog != null){
			pDialog.dismiss();
		}
		if(aQuery.id(R.id.btn_menu_login).getView().getVisibility()==View.VISIBLE)
		{
			aQuery.id(R.id.btn_menu_login).clicked(this);
			aQuery.id(R.id.btn_menu_register).clicked(this);
			getActivity().getSharedPreferences(Constants.SHARED_NAME, Activity.MODE_PRIVATE).edit().putBoolean(Constants.LOGIN, false).commit();
		}else
		{
			aQuery.id(R.id.btn_menu_login).clicked(null);
			aQuery.id(R.id.btn_menu_register).clicked(null);
		}
	}
	
	public void onEventMainThread(LogoutEvent event){
		aQuery.id(R.id.btn_menu_login).visible().clicked(this);
		aQuery.id(R.id.btn_menu_register).visible().clicked(this);
		aQuery.id(R.id.ll_user_info).gone();
		if(settingAdapter.contains(logout)){
			settingAdapter.remove(logout);
		}
		aQuery.id(userInfo).clicked(null);
		settingAdapter.notifyDataSetChanged();
		parentAdapter.notifyDataSetChanged();
		AccessTokenUtil.getInstance().init(getActivity()).saveAccessTokenStr("3de71f9e84a325bbfb86466c15b40b1e");
		((AppStoreVnApplication) getActivity().getApplication()).setAccessToken("3de71f9e84a325bbfb86466c15b40b1e");
		((AppStoreVnApplication) getActivity().getApplication()).setLogin(false);
		getActivity().getSharedPreferences(Constants.SHARED_NAME, Activity.MODE_PRIVATE).edit().putBoolean(Constants.LOGIN, false).commit();
		SharedPreferences mSharedPreferences = getActivity().getApplicationContext().getSharedPreferences(
	                "MyPref", 0);
		mSharedPreferences.edit().putBoolean("isTwitterLogedIn", false).commit();
//		bgTask.getRequestToken();
		if(pDialog != null){
			pDialog.dismiss();
		}
	}
	
	public void onEventMainThread(RequestTokenEvent event){
		if(TextUtils.isEmpty(event.getRequestToken())){
			forceCloseTheApp();
		} else {
			bgTask.getAccessToken(event.getRequestToken());
		}
		if(pDialog != null){
			pDialog.dismiss();
		}
	}
	
	public void onEventMainThread(GetAccessTokenFailEvent event){
		if(pDialog != null){
			pDialog.dismiss();
		}
		forceCloseTheApp();
	}
	
	public void onEventMainThread(GetAccessTokenSuccessEvent event){
		AccessToken accessToken = event.getAt();
		((AppStoreVnApplication) getActivity().getApplication()).setAccessToken(accessToken.getAccessToken());
		((AppStoreVnApplication) getActivity().getApplication()).setCountryCode(accessToken.getCountryCode());
		Editor editor = getActivity().getSharedPreferences(Constants.SHARED_NAME, Activity.MODE_PRIVATE).edit();
		editor.putString(Constants.REFRESH_TOKEN_KEY, accessToken.getRefreshToken());
		AccessTokenUtil.getInstance().init(getActivity()).saveAccessTokenStr(accessToken.getAccessToken());
		AccessTokenUtil.getInstance().init(getActivity()).saveAccessTokenExpires(accessToken.getExpiresIn());
		editor.commit();
		if(pDialog!=null && pDialog.isShowing()){
			pDialog.dismiss();
		}
	}
	
	public void onEventMainThread(UserInfoSuccessEvent event){
		Log.e("uise","uise");
		UserInfo user = event.getUser();
		userName = user.getUserName();
		UILApplication.getInstance().username=userName;
		birthday=user.getBirthday();
		greenTym = user.getGreenTym();
		purpleTym = user.getPurpleTym();
//		TapjoyConnect.getTapjoyConnectInstance().setUserID(userName);
		aq.id(R.id.btn_menu_login).gone();
		aq.id(R.id.btn_menu_register).gone();
		aq.id(R.id.btn_menu_login).clicked(null);
		aq.id(R.id.btn_menu_register).clicked(null);
		aQuery.id(R.id.ll_user_info).visibility(View.VISIBLE);
		aQuery.id(R.id.img_user_avatar).image(user.getAvatarUr(), false, true, 0, 0, null, AQuery.FADE_IN, 1.0f/1.0f);
		aQuery.id(R.id.user_name).text(user.getUserName().toUpperCase(Locale.getDefault()));
		aQuery.id(R.id.green_tym).text(String.valueOf(user.getGreenTym()));
		aQuery.id(R.id.purple_tym).text(String.valueOf(user.getPurpleTym()));
		aQuery.id(R.id.yellow_tym).text(String.valueOf(user.getYellowTym()));
		if(!settingAdapter.contains(logout)){
			settingAdapter.add(logout);
		}
		settingAdapter.notifyDataSetChanged();
		parentAdapter.notifyDataSetChanged();
		if(pDialog != null){
			pDialog.dismiss();
		}
		getActivity().getSharedPreferences(Constants.SHARED_NAME, Activity.MODE_PRIVATE).edit().putBoolean(Constants.LOGIN, true).commit();
		getActivity().getSharedPreferences(Constants.SHARED_NAME, Activity.MODE_PRIVATE).edit().putString(Constants.USERNAME_LOGGEDIN, userName).commit();
//		new CheckBirthdayAsyn().execute();
	}
	private class CheckBirthdayAsyn extends AsyncTask<Void, Void, Void>
	{

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			checkBirthDay("check");
			return null;
		}
		
	}
	private class MenuListItem {
		public String tag;
		public int iconRes;
		@SuppressWarnings("unused")
		public int hotTag;
		public MenuListItem(String tag, int iconRes, int hotTag) {
			this.tag = tag; 
			this.iconRes = iconRes;
			this.hotTag = hotTag;
		}
	}

	public class MenuListAdapter extends ArrayAdapter<MenuListItem> {
		
		private List<MenuListItem> listItem;

		public MenuListAdapter(Context context, int resourceId, List<MenuListItem> list) {
			super(context, R.layout.row, list);
			this.listItem = list;
		}
		
		public boolean contains(MenuListItem item){
			if(listItem.contains(item)){
				return true;
			} else {
				return false;
			}
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(getContext()).inflate(R.layout.row, null);
			}
			ImageView icon = (ImageView) convertView.findViewById(R.id.row_icon);
			icon.setImageResource(getItem(position).iconRes);
			TextView title = (TextView) convertView.findViewById(R.id.row_title);
			title.setText(getItem(position).tag);
			title.setTypeface(tf);
			title.setSelected(true);
			convertView.setTag("item");
			return convertView;
		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_menu_login:
			Intent login = new Intent(getActivity(), LoginActivity.class);
			startActivity(login);
			break;
		case R.id.btn_menu_register:
			Intent register = new Intent(getActivity(), RegisterActivity.class);
			register.putExtra(Constants.LOGIN_TYPE, "normal");
			startActivity(register);
			break;
		}
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		eventBus.unregister(this);
		getActivity().unregisterReceiver(receiver);
		getActivity().unregisterReceiver(loginReceiver);
//		TapjoyConnect.getTapjoyConnectInstance().sendShutDownEvent();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View v, int pos, long arg3) {
		// TODO Auto-generated method stub
		if (null == v.getTag()) {
			return;
		}
		String accessToken = "";
		switch (pos) {
		case 2: 
		toggleMenuWhenClick(new ISlidingMenuClosed() {
			@Override
			public void onSlideMenuClosed() {
				// TODO Auto-generated method stub
				EasyTracker.getTracker().sendEvent(Constants.EVENT,Constants.EVENT_ACTION, "NewsFeedActivity", Long.valueOf(1));
//				Intent news = new Intent(getActivity(), NewsFeedActivity.class);
//				news.putExtra(Constants.STATE, 0);
//				startActivity(news);
				HomeActivity.setIndex(1);
			}
		});
		break;
		case 4:
			toggleMenuWhenClick(new ISlidingMenuClosed() {
				@Override
				public void onSlideMenuClosed() {
					Intent manage = new Intent(getActivity(), AppManageActivity.class);
					manage.putExtra(Constants.STORE_KEY, "apps");
					manage.putExtra("index", 2);
					startActivity(manage);
				}
			});
			break;
		case 6:
		toggleMenuWhenClick(new ISlidingMenuClosed() {
			@Override
			public void onSlideMenuClosed() {
				Intent intent = new Intent(getActivity(), SettingsActivity.class);
				startActivity(intent);
			}
		});
		break;
	case 9:
		//change to about
		Intent about = new Intent(getActivity(), AboutActivity.class);
		startActivity(about);
		break;
//		///
//		AlertDialogManager am = new AlertDialogManager(getActivity());
//		String[] items = getResources().getStringArray(R.array.more);
//		am.showDialogWithItems(R.string.more_settings, items, new DialogInterface.OnClickListener() {
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				// TODO Auto-generated method stub
//				switch (which) {
////				case 0:
////					Intent qrcode = new Intent(getActivity(), CaptureActivity.class);
////					startActivity(qrcode);
////					break;
//				case 0:
//					Intent about = new Intent(getActivity(), AboutActivity.class);
//					startActivity(about);
//					break;
//				case 1:
//					pDialog = ProgressDialogManager.showProgressDialog(getActivity(), R.string.loading);
//					bgTask.checkClientUpdate(String.valueOf(Utils.getStaticIsRooted(getActivity())));
//					break;
//				case 2:
//					Intent um = new Intent(Intent.ACTION_VIEW);
//					um.setData(Uri.parse("http://apptoko.com/manual/android"));
//					startActivity(um);
//					break;
//				case 3:
//					Intent tutor = new Intent(getActivity(), TutorialActivity.class);
//					tutor.putExtra(Constants.TUTOR_POS, 10);
//					startActivity(tutor);
//					break;
//				}
//			}
//		});
//		break;
	case 8:
		//user manual
//		Intent um = new Intent(Intent.ACTION_VIEW);
//		um.setData(Uri.parse("http://apptoko.com/manual/android"));
//		startActivity(um);
		if(pCancelableDialog!=null && !pCancelableDialog.isShowing()){
			pCancelableDialog.show();
		}
		String lang=getResources().getString(R.string.lang);
		String manual=(lang.equalsIgnoreCase("id")?CommonUtils.USER_MANUAL_ID_PATH:CommonUtils.USER_MANUAL_PATH);
		File savedManual=new File(manual);
		if(savedManual.exists()){
			pCancelableDialog.dismiss();
			Intent loginIntent = new Intent(getActivity(), UserManualView.class);
			loginIntent.putExtra("url", manual);
			startActivity(loginIntent);
		}else{
			bgTask.getUserManual(Utils.getStaticAccessToken(getActivity()),getResources().getString(R.string.lang));
		}
		
		break;
	case 7:
		//feedback
		FeedBackDialog customDialog = new FeedBackDialog(getActivity(),0,getResources().getString(R.string.commonfeedback),userName==null?getResources().getString(R.string.visitorfeedback):userName);
		customDialog.setTitle(R.string.feed_back);
		customDialog.show();
		break;
	
	case 10:
		//logout
		pDialog = ProgressDialogManager.showProgressDialog(getActivity(), R.string.logout_ing);
		accessToken = Utils.getStaticAccessToken(getActivity());
		bgTask.logOut(accessToken);
		break;
//		case 2: 
//			toggleMenuWhenClick(new ISlidingMenuClosed() {
//				@Override
//				public void onSlideMenuClosed() {
//					// TODO Auto-generated method stub
//					EasyTracker.getTracker().sendEvent(Constants.EVENT,Constants.EVENT_ACTION, "NewsFeedActivity", Long.valueOf(1));
//					Intent news = new Intent(getActivity(), NewsFeedActivity.class);
//					news.putExtra(Constants.STATE, 0);
//					startActivity(news);
//				}
//			});
//			break;
//		case 4:
//			//spin
//			toggleMenuWhenClick(new ISlidingMenuClosed() {
//				@Override
//				public void onSlideMenuClosed() {
////					Intent spin = new Intent(getActivity(), FirstScreen.class);
////					startActivityForResult(spin, Constants.SPIN_REQUEST_CODE);
//				}
//			});
//			break;
//		case 5:
//			toggleMenuWhenClick(new ISlidingMenuClosed() {
//				@Override
//				public void onSlideMenuClosed() {
//					Intent spin = new Intent(getActivity(), ShopActivity.class);
//					startActivity(spin);
//				}
//			});
//			break;
//		case 6://get free Yellow TYM
//			toggleMenuWhenClick(new ISlidingMenuClosed() {
//				@Override
//				public void onSlideMenuClosed() {
//					Intent gc = new Intent(getActivity(), GiftCodeActivity.class);
//					gc.putExtra(apptoko.com.util.Constants.USER_NAME, userName);
//					getActivity().startActivity(gc);
//				}
//			});
//			break;
//		case 7:
//			toggleMenuWhenClick(new ISlidingMenuClosed() {
//				@Override
//				public void onSlideMenuClosed() {
//					getFreeGreenTYM();
//				}
//			});
//			break;
//		case 8:
//			toggleMenuWhenClick(new ISlidingMenuClosed() {
//				@Override
//				public void onSlideMenuClosed() {
//					getFreePurpleTYM();
//				}
//			});
//			break;
//		case 9:
////			AlertDialogManager am1 = new AlertDialogManager(getActivity());
////			am1.showPositiveDialog(R.string.coming_soon, R.string.ok, new DialogInterface.OnClickListener() {
////				@Override
////				public void onClick(DialogInterface dialog, int which) {
////					// TODO Auto-generated method stub
////					dialog.dismiss();
////				}
////			});
//			toggleMenuWhenClick(new ISlidingMenuClosed() {
//				@Override
//				public void onSlideMenuClosed() {
//					getFreeYellowTYM();
//				}
//			});
//			break;
//		case 11:
//			if(checkLogin()){
//				List<String> scopes = new ArrayList<String>();
//				scopes.add("user.info");
//				scopes.add("user.email");
//				TopupAPI.getInstance().setContext(getActivity()).topupTYM(scopes, userName);
////				pDialog = ProgressDialogManager.showProgressDialog(getActivity(), R.string.loading);
////				accessToken = Utils.getStaticAccessToken(getActivity());
////				bgTask.buyTYMSMS("menu", accessToken);
//			} else {
//				showLogin();
//			}
//			break;
////		case 11:
////			//tym card
////			Intent card = new Intent(getActivity(), CardPaymentActivity.class);
////			startActivity(card);
////			break;
////		case 12:
////			if(checkLogin()){
////				dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
////		        dialog.setContentView(R.layout.layout_tym_sms);
////		        dialog.setCancelable(true);
////		        final List<BankOption> listBankOption = new ArrayList<BankOption>();
////		        listBankOption.add(new BankOption(479, 50000));
////		        listBankOption.add(new BankOption(974, 100000));
////		        listBankOption.add(new BankOption(1964, 200000));
////		        listBankOption.add(new BankOption(4934, 500000));
////		        listBankOption.add(new BankOption(9884, 1000000));
////		        listBankOption.add(new BankOption(19784, 2000000));
////		        ((TextView)dialog.findViewById(R.id.dialog_title)).setText(R.string.buy_tym_bank);
////		        BankTYMAdapter adapter = new BankTYMAdapter(getActivity().getApplicationContext(), R.layout.sms_item, listBankOption);
////		        HorizontalListView listSMS = (HorizontalListView)dialog.findViewById(R.id.sms_list);
////		        listSMS.setAdapter(adapter);
////		        listSMS.setOnItemClickListener(new OnItemClickListener() {
////					@Override
////					public void onItemClick(AdapterView<?> parent, View v, int pos, long arg3) {
////						pDialog = ProgressDialogManager.showProgressDialog(getActivity(), R.string.loading);
////						MenuFragment.this.accessToken = Utils.getStaticAccessToken(getActivity());
////						bgTask.buyTYMBank(MenuFragment.this.accessToken, String.valueOf(listBankOption.get(pos).getAmount()));
////					}
////				});
////		        ((Button)dialog.findViewById(R.id.btn_close_dialog)).setOnClickListener(new OnClickListener() {
////					@Override
////					public void onClick(View v) {
////						dialog.dismiss();
////					}
////				});
////		        dialog.show();
////			} else {
////				showLogin();
////			}
////			break;
////		case 13:
////			if(checkLogin()){
////				dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
////		        dialog.setContentView(R.layout.layout_tym_sms);
////		        dialog.setCancelable(true);
////		        final List<PaypalPayment> listPaypal = new ArrayList<PaypalPayment>();
////		        listPaypal.add(new PaypalPayment(5, 850));
////		        listPaypal.add(new PaypalPayment(10, 1700));
////		        listPaypal.add(new PaypalPayment(50, 8500));
////		        ((TextView)dialog.findViewById(R.id.dialog_title)).setText(R.string.buy_tym_paypal);
////		        PaypalTYMAdapter ppAdapter = new PaypalTYMAdapter(getActivity().getApplicationContext(), R.layout.sms_item, listPaypal);
////		        HorizontalListView listPP = (HorizontalListView) dialog.findViewById(R.id.sms_list);
////		        listPP.setAdapter(ppAdapter);
////		        listPP.setOnItemClickListener(new OnItemClickListener() {
////					@Override
////					public void onItemClick(AdapterView<?> parent, View v, int pos, long arg3) {
////						pDialog = ProgressDialogManager.showProgressDialog(getActivity(), R.string.loading);
////						MenuFragment.this.accessToken = Utils.getStaticAccessToken(getActivity());
////						bgTask.buyTYMPaypal(MenuFragment.this.accessToken, String.valueOf(listPaypal.get(pos).getAmount()));
////					}
////				});
////		        ((Button)dialog.findViewById(R.id.btn_close_dialog)).setOnClickListener(new OnClickListener() {
////					@Override
////					public void onClick(View v) {
////						dialog.dismiss();
////					}
////				});
////		        dialog.show();
////			} else {
////				showLogin();
////			}
////			break;
//		case 12:
//			//exchange
//			if(checkLogin()){
//				Intent ex = new Intent(getActivity(), ExchangeTymActivity.class);
//				ex.putExtra(Constants.GREEN_TYM, greenTym);
//				startActivity(ex);
//			} else {
//				showLogin();
//			}
//			break;
//		case 14:
//			toggleMenuWhenClick(new ISlidingMenuClosed() {
//				@Override
//				public void onSlideMenuClosed() {
//					Intent intent = new Intent(getActivity(), SettingsActivity.class);
//					startActivity(intent);
//				}
//			});
//			break;
//		case 15:
//			AlertDialogManager am = new AlertDialogManager(getActivity());
//			String[] items = getResources().getStringArray(R.array.more);
//			am.showDialogWithItems(R.string.more_settings, items, new DialogInterface.OnClickListener() {
//				@Override
//				public void onClick(DialogInterface dialog, int which) {
//					// TODO Auto-generated method stub
//					switch (which) {
////					case 0:
////						Intent qrcode = new Intent(getActivity(), CaptureActivity.class);
////						startActivity(qrcode);
////						break;
//					case 0:
//						Intent about = new Intent(getActivity(), AboutActivity.class);
//						startActivity(about);
//						break;
//					case 1:
//						pDialog = ProgressDialogManager.showProgressDialog(getActivity(), R.string.loading);
//						bgTask.checkClientUpdate(String.valueOf(Utils.getStaticIsRooted(getActivity())));
//						break;
//					case 2:
//						Intent um = new Intent(Intent.ACTION_VIEW);
//						um.setData(Uri.parse("http://appstore.vn/manual/android"));
//						startActivity(um);
//						break;
//					case 3:
//						Intent tutor = new Intent(getActivity(), TutorialActivity.class);
//						tutor.putExtra(Constants.TUTOR_POS, 10);
//						startActivity(tutor);
//						break;
//					}
//				}
//			});
//			break;
//		case 16:
//			//feedback
//			FeedBackDialog customDialog = new FeedBackDialog(getActivity(),0,getResources().getString(R.string.commonfeedback),userName==null?getResources().getString(R.string.visitorfeedback):userName);
//			customDialog.setTitle(R.string.feed_back);
//			customDialog.show();
//			break;
//		
//		case 17:
//			//logout
//			pDialog = ProgressDialogManager.showProgressDialog(getActivity(), R.string.logout_ing);
//			accessToken = Utils.getStaticAccessToken(getActivity());
//			bgTask.logOut(accessToken);
//			break;
		}
	}
	
	private boolean checkLogin(){
		return Utils.getStaticIsLogin(getActivity());
	}
	
	public void onEventMainThread(LogoutFailed e){
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
		Toast.makeText(getActivity(), R.string.logout_failed, Toast.LENGTH_SHORT).show();
	}
	
	private void showLogin(){
		AlertDialogManager am = new AlertDialogManager(getActivity());
		am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				switch (which) {
				case DialogInterface.BUTTON_POSITIVE:
					Intent intent = new Intent(getActivity(), LoginActivity.class);
					startActivity(intent);
					break;
				case DialogInterface.BUTTON_NEGATIVE:
					dialog.dismiss();
					break;
				}
			}
		});
	}
	
	private void forceCloseTheApp(){
		AlertDialog.Builder builder=new Builder(getActivity());
		builder.setMessage(R.string.error).setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
				getActivity().finish();
			}
		}).create().show();
	}
	
//	public void onEventMainThread(final TYMSMSEvent event){
//		if(event.getFrom().equalsIgnoreCase("menu")){
//			if(pDialog != null){
//				pDialog.dismiss();
//			}
//			final Dialog dialog = new Dialog(getActivity());
//			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//	        dialog.setContentView(R.layout.layout_tym_sms);
//	        dialog.setCancelable(true);
//	        SMSTYMAdapter adapter = new SMSTYMAdapter(getActivity().getApplicationContext(), R.layout.sms_item, event.getData().getSmsOptions());
//	        ((TextView)dialog.findViewById(R.id.dialog_title)).setText(R.string.buy_tym_sms);
//	        HorizontalListView listSMS = (HorizontalListView)dialog.findViewById(R.id.sms_list);
//	        listSMS.setAdapter(adapter);
//	        listSMS.setOnItemClickListener(new OnItemClickListener() {
//				@Override
//				public void onItemClick(AdapterView<?> parent, View v, int pos, long arg3) {
//					SMSOption sms = (SMSOption) parent.getItemAtPosition(pos);
//					EasyTracker.getTracker().sendEvent(Constants.BUY_EVENT_ACTION, Constants.BUY_TYM, "buy tym by sms: " + sms.getSyntax() + " send " + sms.getSendNumber(), Long.valueOf(1));
//					Intent i = new Intent(Intent.ACTION_VIEW);
//					i.putExtra("address", sms.getSendNumber());
//					i.putExtra("sms_body", sms.getSyntax());
//					i.setType("vnd.android-dir/mms-sms");
//					startActivity(i);
//					accessToken = Utils.getStaticAccessToken(getActivity());
//					bgTask.checkTopupResult(accessToken, event.getData().getTransactionID());
//				}
//			});
//	        ((Button)dialog.findViewById(R.id.btn_close_dialog)).setOnClickListener(new OnClickListener() {
//				@Override
//				public void onClick(View v) {
//					dialog.dismiss();
//				}
//			});
//	        dialog.show();
//		}
//	}
	
	public void onEventMainThread(SMSTYMFailEvent event){
		if(pDialog != null){
			pDialog.dismiss();
		}
		ErrorHandler.getInstance().setContext(getActivity()).handleError(event.getErrorCode());
	}
	
//	public void onEventMainThread(TYMBankSuccessEvent event){
//		if(pDialog != null){
//			pDialog.dismiss();
//		}
//		BankPayment bank = event.getData();
//		Intent intent = new Intent(getActivity(), BankPaymentActivity.class);
//		intent.putExtra(Constants.BANK_PAYMENT_DATA, bank);
//		startActivityForResult(intent, Constants.TOPUP_BANK_REQUEST_CODE);
//	}
	
//	public void onEventMainThread(TYMPaypalSuccessEvent event){
//		if(pDialog != null){
//			pDialog.dismiss();
//		}
//		Intent paypalIntent = new Intent(getActivity(), PaypalActivity.class);
//		Bundle b = new Bundle();
//		b.putSerializable(Constants.PAYPAL_DATA, event.getData());
//		paypalIntent.putExtras(b);
//		startActivityForResult(paypalIntent, Constants.TOPUP_PAYPAL_REQUEST_CODE);
//	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, final Intent data){
		if(requestCode == Constants.TOPUP_BANK_REQUEST_CODE && resultCode == Activity.RESULT_OK){
			accessToken = Utils.getStaticAccessToken(getActivity());
			AsyncExecutor.create().execute(new RunnableEx() {
				@Override
				public void run() throws Exception {
					AppMsg.makeText(getActivity(), R.string.transaction_request_sent, AppMsg.STYLE_INFO, null).show();
					BankPayment bank = (BankPayment) data.getExtras().getSerializable(Constants.BANK_PAYMENT_DATA);
					bgTask.checkTopupResult(accessToken, bank.getTransactionId());
				}
			});
		} else if(requestCode == Constants.TOPUP_PAYPAL_REQUEST_CODE && resultCode == Activity.RESULT_OK){
			accessToken = Utils.getStaticAccessToken(getActivity());
			AsyncExecutor.create().execute(new RunnableEx() {
				@Override
				public void run() throws Exception {
					AppMsg.makeText(getActivity(), R.string.transaction_request_sent, AppMsg.STYLE_INFO, null).show();
					bgTask.checkTopupResult(accessToken, data.getStringExtra(Constants.TRANSACTION_ID_KEY));
				}
			});
		} else if(requestCode == Constants.SPIN_REQUEST_CODE && resultCode == Activity.RESULT_OK){
			accessToken = Utils.getStaticAccessToken(getActivity());
			if(accessToken!="3de71f9e84a325bbfb86466c15b40b1e"){
				bgTask.getUserInfo(accessToken);
			}
			
		} else if(requestCode == com.appota.ads.commons.Constants.OFFER_REQUEST_CODE && resultCode == Activity.RESULT_OK){
			AlertDialogManager am = new AlertDialogManager(getActivity());
			am.showDialog(String.format(getResources().getString(R.string.receive_free_tym), data.getIntExtra(com.appota.ads.commons.Constants.REWARD, 0)), new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					String accessToken = Utils.getStaticAccessToken(getActivity());
					if(accessToken!="3de71f9e84a325bbfb86466c15b40b1e"){
						bgTask.getUserInfo(accessToken);
					}
					dialog.dismiss();
				}
			});
		}
	}
	
	public void onEventMainThread(GiftCodeEvent e){
		accessToken = Utils.getStaticAccessToken(getActivity());
		if(accessToken!="3de71f9e84a325bbfb86466c15b40b1e"){
			bgTask.getUserInfo(accessToken);
		}
	}
	
	public void onEventMainThread(BankTYMFailEvent event){
		if(pDialog != null){
			pDialog.dismiss();
		}
		ErrorHandler.getInstance().setContext(getActivity()).handleError(event.getErrorCode());
	}
	
	public void onEventMainThread(PaypalTYMFailEvent event){
		if(pDialog != null){
			pDialog.dismiss();
		}
		ErrorHandler.getInstance().setContext(getActivity()).handleError(event.getErrorCode());
	}
	
	public void onEventMainThread(TopupSuccessEvent event){
		EasyTracker.getTracker().sendEvent(Constants.BUY_EVENT_ACTION, Constants.BUY_TYM_SUCCESS, event.getResult().getAmount() + " at " + Utils.convertUnixTime(event.getResult().getTime()), Long.valueOf(100));
		Toast.makeText(getActivity(), event.getResult().getMessage(), Toast.LENGTH_SHORT).show();
		accessToken = Utils.getStaticAccessToken(getActivity());
		if(accessToken!="3de71f9e84a325bbfb86466c15b40b1e"){
			bgTask.getUserInfo(accessToken);
		}
	}
	
	public void onEventMainThread(TopupFailEvent event){
		ErrorHandler.getInstance().setContext(getActivity()).handleError(event.getErrorCode());
	}
	
//	public void onEventMainThread(AppStoreVnUpdateData data){
//		if(pDialog != null){
//			pDialog.dismiss();
//		}
//		String updateUri;
//		if(data.isForce()){
//			updateUri = data.getUpdateUrl();
//			DownloadUpdateTask task = new DownloadUpdateTask(getActivity());
//			task.setDownloadCallback(MenuFragment.this);
//			task.execute(updateUri);
//		} else {
//			Intent showUpdate = new Intent(getActivity(), PopupUpdateActivity.class);
//			Bundle bundle = new Bundle();
//			bundle.putSerializable(Constants.KEY_UPDATE_DATA, data);
//			showUpdate.putExtras(bundle);
//			startActivityForResult(showUpdate, Constants.UPDATE_REQUEST_CODE);
//		}
//	}
	
	public void onEventMainThread(Event.LatestVersionEvent event){
		if(pDialog != null){
			pDialog.dismiss();
		}
		Toast.makeText(getActivity(), R.string.updated_latest, Toast.LENGTH_SHORT).show();
	}
	
	private void toggleMenuWhenClick(ISlidingMenuClosed l) {
		if (null == getActivity()) {
			return;
		}
		if (getActivity() instanceof HomeActivity) {
			HomeActivity activity = (HomeActivity) getActivity();
			activity.setISlidingMenuListener(l);
			activity.toggleMenu();
		}
	}
	
	private void getFreeYellowTYM(){
		if(checkLogin()){
			AppotaAds.getInstance().init(getActivity()).getOfferWall(userName, "duydkny");
		} else {
			AlertDialog.Builder info = new AlertDialog.Builder(getActivity());
			info.setMessage(R.string.login_get_free_tym);
			info.setPositiveButton(android.R.string.ok,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							Intent intent = new Intent(getActivity(), LoginActivity.class);
							startActivity(intent);
						}
					});
			info.show();
		}
//		EasyTracker.getTracker().sendEvent(Constants.EVENT,Constants.EVENT_ACTION, "GetFreeYellowTYM", Long.valueOf(1));
//			boolean isLogin = Utils.getStaticIsLogin(getActivity());
//			if (!isLogin) {
//				AlertDialog.Builder info = new AlertDialog.Builder(getActivity());
//				info.setMessage(R.string.login_get_free_tym);
//				info.setPositiveButton(android.R.string.ok,
//						new DialogInterface.OnClickListener() {
//							@Override
//							public void onClick(DialogInterface arg0, int arg1) {
//								Intent intent = new Intent(getActivity(), LoginActivity.class);
//								startActivity(intent);
//							}
//						});
//				info.show();
//			} else {
//				Intent rating = new Intent(getActivity(), RatingActivity.class);
//				startActivity(rating);
//			}
	}
	
	private void getFreeGreenTYM(){
		EasyTracker.getTracker().sendEvent(Constants.EVENT,Constants.EVENT_ACTION, "GetFreeGreenTYM", Long.valueOf(1));
		if(enableFreeTym == 1){
			boolean isLogin = Utils.getStaticIsLogin(getActivity());
			if (!isLogin) {
				AlertDialog.Builder info = new AlertDialog.Builder(getActivity());
				info.setMessage(R.string.login_get_free_tym);
				info.setPositiveButton(android.R.string.ok,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								Intent intent = new Intent(getActivity(), LoginActivity.class);
								//intent.putExtra(DetailsActivity.IS_BROADCAST, 1);
								startActivity(intent);
							}
						});
				info.show();
			} else {
				try {
					String random = Utils.generateRandomString(32);
					String input = random + userName;
					SCENARIO = random + Utils.generateHashMD5(input);
//					Intent intent = MetapsFactory.getIntent(getActivity(), userName, SCENARIO);
//					startActivity(intent);
				} catch (Exception e) {
					Log.e("SampleActivity", "Exception : "+e.getClass().getName()+" "+e.getMessage());
				}
			}
		} else {
			AlertDialog.Builder info = new AlertDialog.Builder(getActivity());
			info.setMessage(R.string.disable_free_tym);
			info.setPositiveButton(android.R.string.ok,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							arg0.dismiss();
						}
					});
			info.show();
		}
	}
	
	private void getFreePurpleTYM(){
		EasyTracker.getTracker().sendEvent(Constants.EVENT,Constants.EVENT_ACTION, "menu-free-purple-tym", Long.valueOf(1));
		if(enableFreeTym == 1){
			boolean isLogin = Utils.getStaticIsLogin(getActivity());
			if (!isLogin) {
				AlertDialog.Builder info = new AlertDialog.Builder(getActivity());
				info.setMessage(R.string.login_get_free_tym);
				info.setPositiveButton(android.R.string.ok,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								Intent intent = new Intent(getActivity(), LoginActivity.class);
								//intent.putExtra(DetailsActivity.IS_BROADCAST, 1);
								startActivity(intent);
							}
						});
				info.show();
			} else {
//				TapjoyConnect.getTapjoyConnectInstance().showOffersWithCurrencyID("3622bb41-0c54-4057-8dc3-4defc6bf0e34", false);
			}
		} else {
			AlertDialog.Builder info = new AlertDialog.Builder(getActivity());
			info.setMessage(R.string.disable_free_tym);
			info.setPositiveButton(android.R.string.ok,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							arg0.dismiss();
						}
					});
			info.show();
		}
	}
	
	
//	private class MyReceiver implements Receiver {
//		private int point = 0;
//
//		@Override
//		public boolean retrieve(int currencyAmount, TapHistory tap) {
//			this.point += currencyAmount;
//			AlertDialogManager am = new AlertDialogManager(getActivity());
//			am.showDialog(String.format(getResources().getString(R.string.receive_free_tym), point), new DialogInterface.OnClickListener() {
//				
//				@Override
//				public void onClick(DialogInterface dialog, int which) {
//					// TODO Auto-generated method stub
//					String accessToken = Utils.getStaticAccessToken(getActivity());
//					if(accessToken!="3de71f9e84a325bbfb86466c15b40b1e"){
//						bgTask.getUserInfo(accessToken);
//					}
//					dialog.dismiss();
//				}
//			});
//			return true;
//		}
//
//		@Override
//		public boolean finalizeOnError(TapHistory tap) {
//			return true;
//		}
//	}
	private class ReloadLogin extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if(TextUtils.equals(action, "LOGGEDIN_AND_RELOAD")){
				String tk = intent.getStringExtra("tk");
				Log.e("ReloadLogin","ReloadLogin receiver with tk:"+tk);
				doReload(tk);
			}
		}

	}
	private class CPIAReceiver extends AppotaReceiver {

		@Override
		public void onRetrieve(int rewardPoint) {
			// TODO Auto-generated method stub
			Toast.makeText(getActivity(), rewardPoint + "", Toast.LENGTH_SHORT).show();
			AlertDialogManager am = new AlertDialogManager(getActivity());
			am.showDialog(String.format(getResources().getString(R.string.receive_free_yellow_tym), rewardPoint), new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					String accessToken = Utils.getStaticAccessToken(getActivity());
					if(accessToken!="3de71f9e84a325bbfb86466c15b40b1e"){
						bgTask.getUserInfo(accessToken);
					}
					dialog.dismiss();
				}
			});
		}
	}

	@Override
	public void onDownloadComplete(String path) {
		// TODO Auto-generated method stub
		Utils.installAPK(getActivity(), path);
		getActivity().finish();
	}

	@Override
	public void onDownloadError() {
		// TODO Auto-generated method stub
		
	}
	
	public void onEventMainThread(ExchangeTYMSuccessEvent event){
		Toast.makeText(getActivity(), event.getData().getMessage(), Toast.LENGTH_SHORT).show();
		greenTym = event.getData().getGreenTym();
		purpleTym = event.getData().getPurpleTym();
		aQuery.id(R.id.purple_tym).text(String.valueOf(purpleTym));
		aQuery.id(R.id.green_tym).text(String.valueOf(greenTym));
	}
	
	public void onEventMainThread(ReportGiftboxSuccess e){
		if(e.getType().equalsIgnoreCase("confirm")){
			if(accessToken!="3de71f9e84a325bbfb86466c15b40b1e"){
				bgTask.getUserInfo(accessToken);
			}
		}
	}
	
	private void checkGift(){
		accessToken = Utils.getStaticAccessToken(getActivity());
		List<GiftSetting> gifts = db.getAllPendingGift();
		long now = System.currentTimeMillis() / 1000L;
		if(gifts.size() > 0){
			for(int i = 0; i < gifts.size(); i++){
				System.err.println("now: " + now + " time to receive: " + gifts.get(i).getTimeToReceive());
				if(gifts.get(i).getTimeToReceive() <= now && Utils.appInstalledOrNot(getActivity(), gifts.get(i).getName())){
					bgTask.reportGiftbox(accessToken, gifts.get(i).getSlug(), "check", gifts.get(i).getName());
				}
			}
		}
	}
	
	private void syncGift(){
		accessToken = Utils.getStaticAccessToken(getActivity());
		bgTask.getSettingList(accessToken);
	}
	
	public void onEventMainThread(GetSettingListSuccess e){
		accessToken = Utils.getStaticAccessToken(getActivity());
		bgTask.getAllSettingDetails(accessToken, e.getList());
	}
	
	public void onEventMainThread(GetSettingDetailsListSuccess e){
		List<GiftSetting> giftList = e.getListGift();
		db.truncateTableGiftSync();
		db.syncGift(giftList);
	}
	public void onEventMainThread(CheckUserBirthdayFailedWithMsg e){
		Log.e("OneventMainThread","CheckUserBirthdayFailedWithMsg");
	}
	public void onEventMainThread(CheckUserBirthdaySucceed e){
		Log.e("OneventMainThread","CheckUserBirthdaySucceed");
		//start send request for show notification
		//show notification
		if(e.getReceived()==0)
		{
			NotificationManager notiManager=(NotificationManager) getActivity().getSystemService(getActivity().NOTIFICATION_SERVICE);
	    	Notification notification = new Notification(R.drawable.ic_launcher, 
					getResources().getString(R.string.msg_title_notification_birthday), System.currentTimeMillis());
	    	notification.flags = Notification.FLAG_AUTO_CANCEL;
	    	notification.defaults |= Notification.DEFAULT_SOUND;
	    	notification.defaults |= Notification.DEFAULT_VIBRATE;
			Intent notificationIntent = new Intent(getActivity(), BirthdayDialogActivity.class);
			notificationIntent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
			notificationIntent.putExtra("gold_tym", e.getNum_of_gold_tym());
			PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(), 0,
					notificationIntent, 0);
			notification.setLatestEventInfo(getActivity(), getResources().getString(R.string.msg_title_notification_birthday),
					getResources().getString(R.string.msg_content_notification_birthday),
					pendingIntent);
			notiManager.notify(2324, notification);
		}
		
	}
	private void checkBirthDay(String type){
		if(!checkLogin()||is_check_birthday)
		{
			return;
		}
		SharedPreferences shared=getActivity().getPreferences(Activity.MODE_PRIVATE);
		long previous_check=shared.getLong("last_check_birthday", 0);
		if(previous_check!=0)
		{
			Calendar c = Calendar.getInstance();
			c.setTime(new Date());
			int current_month=c.get(Calendar.MONTH);
			int current_day=c.get(Calendar.DATE);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String time = sdf.format(c.getTime());
			long unixTime = 0;
			try {
				unixTime = sdf.parse(time).getTime() / 1000L;
				Log.e("CheckBirthday","today:"+unixTime+", previous:"+previous_check);
				if(unixTime-previous_check>0||type.equals("confirm"))
				{
					//not checked yet -> going to check
					//check birthday
					is_check_birthday=true;
					Date date=null;
					try {  
						if(!birthday.equals("0000-00-00"))
						{
							date = sdf.parse(birthday);  
							System.out.println(date); 
						}
					     
					} catch (ParseException e) {  
					    // TODO Auto-generated catch block  
					}
					if(date==null)
					{
						return;
					}
					c.setTime(date);
					int b_month=c.get(Calendar.MONTH);
					int b_day=c.get(Calendar.DATE);
					Log.e("Birthday",birthday);
					Log.e("CheckBirthday","current date - current month - bdate - bmonth:"+current_day+" - "+current_month+" - "+b_day+" - "+b_month);
					if(b_month==current_month&&b_day==current_day)
					{
						//show notification
						HttpHelper.checkUserBirthday("check", Utils.getStaticAccessToken(getActivity()));
					}
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}else
		{
			//the first check
			Calendar c = Calendar.getInstance();
			c.setTime(new Date());
			int current_month=c.get(Calendar.MONTH);
			int current_day=c.get(Calendar.DATE);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String time = sdf.format(c.getTime());
			Date date=null;
			try {  
				if(!birthday.equals("0000-00-00"))
				{
					date = sdf.parse(birthday);  
					System.out.println(date); 
				}  
			} catch (ParseException e) {  
			    // TODO Auto-generated catch block  
			}
			if(date==null)
			{
				return;
			}
			c.setTime(date);
			int b_month=c.get(Calendar.MONTH);
			int b_day=c.get(Calendar.DATE);
			long unixCurrentTime = 0;
			Log.e("Birthday",birthday);
			is_check_birthday=true;
			try {
				unixCurrentTime = sdf.parse(time).getTime() / 1000L;
				Log.e("CheckBirthday","today:"+unixCurrentTime+", previous:"+previous_check);
				Log.e("CheckBirthday","current date - current month - bdate - bmonth:"+current_day+" - "+current_month+" - "+b_day+" - "+b_month);
				if(b_month==current_month&&b_day==current_day)
				{
					//show notification
					HttpHelper.checkUserBirthday("check", Utils.getStaticAccessToken(getActivity()));
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
			
		}

	}
	public void onEventMainThread(Event.GetUserManualSuccessEvent event){
		if(pCancelableDialog != null&&pCancelableDialog.isShowing()){
			pCancelableDialog.dismiss();
		}
		String lang=getResources().getString(R.string.lang);
		String path=(lang.equalsIgnoreCase("id")?CommonUtils.USER_MANUAL_ID_PATH:CommonUtils.USER_MANUAL_PATH);
		if(CommonUtils.saveUserManual(event.manual,path)){
			Intent loginIntent = new Intent(getActivity(), UserManualView.class);
			loginIntent.putExtra("url",path);
			startActivity(loginIntent);
		}else{
			Toast.makeText(getActivity(), "Get user manual failed", Toast.LENGTH_SHORT).show();
		}
		
	}
	public void onEventMainThread(Event.GetUserManualFailEvent event){
		if(pCancelableDialog != null&&pCancelableDialog.isShowing()){
			pCancelableDialog.dismiss();
		}
		Toast.makeText(getActivity(), "Get user manual failed", Toast.LENGTH_SHORT).show();
	}
}
